﻿using System;
using SoftwareConsulting.BI11.NumericalMethods.ComplexNumbers;

namespace SoftwareConsulting.BI11.NumericalMethods.Statistics
{
    /// <summary>
    /// Класс получения коэффициента корреляции Пирсона
    /// </summary>
    public class PearsonCorrelation
    {
        private double _result;
        
        /// <summary>
        /// Конструктор класса
        /// </summary>
        /// <param name="sample1">выборка 1</param>
        /// <param name="sample2">выборка 2</param>
        /// <param name="sampleSize">размер выборок</param>
        public PearsonCorrelation(double[] sample1, double[] sample2, int sampleSize)
        {
            _result = 0;                                    
            //ищем среднее
            double xmean = 0;
            double ymean = 0;
            for (int i = 0; i <= sampleSize - 1; i++)
            {
                xmean = xmean + sample1[i];
                ymean = ymean + sample2[i];
            }
            xmean = xmean / sampleSize;
            ymean = ymean / sampleSize;
            //делим            
            double s = 0;
            double xv = 0;
            double yv = 0;
            for (int i = 0; i <= sampleSize - 1; i++)
            {
                double t1 = sample1[i] - xmean;
                double t2 = sample2[i] - ymean;
                xv = xv + ComplexMath.Sqr(t1);
                yv = yv + ComplexMath.Sqr(t2);
                s = s + t1 * t2;
            }
            _result = (xv == 0 | yv == 0) ? 
                0 
                : 
                s / (Math.Sqrt(xv) * Math.Sqrt(yv));
        }

        /// <summary>
        /// Возвращает решение
        /// </summary>        
        public double GetSolution()
        {
            return _result;
        }
    }
}
